package losrebellos.lospistoleros.core.controller.events 
{
	import losrebellos.lospistoleros.core.controller.PController;
	import losrebellos.lospistoleros.core.model.IPModel;
	import losrebellos.lospistoleros.core.model.events.IPModelEventDispatcher;
	import losrebellos.lospistoleros.core.view.IPView;
	import losrebellos.lospistoleros.core.view.events.IPViewEventDispatcher;

	import flash.events.Event;

	/*
	 *
	 * @author los rebellos - ben@benoitvinay.com
	 *
	 */
	public class PControllerEventDispatcher extends PController implements IPControllerEventDispatcher
	{
		/*
		 *
		 * VARIABLES
		 *
		 */
		protected var _model:IPModelEventDispatcher;
		protected var _view:IPViewEventDispatcher;
		
		
		/*
		 *
		 * CONSTRUCTOR
		 *
		 */
		public function PControllerEventDispatcher(m:IPModel, v:IPView = null, name:String = null, type:String = null)
		{
			super(m, v, name, type);
		}

		
		/*
		 * 
		 * MVC
		 * 
		 */
		override protected function saveModel(m:IPModel):void
		{
			_model = m as IPModelEventDispatcher;
		}
		public function setModel(m:IPModelEventDispatcher):void
		{
			_model = m;
		}
		public function getModel():IPModelEventDispatcher
		{
			return _model;
		}
		override protected function saveView(v:IPView):void
		{
			_view = v as IPViewEventDispatcher;
		}
		public function setView(v:IPViewEventDispatcher):void
		{
			_view = v;
		}
		public function getView():IPViewEventDispatcher
		{
			return _view;
		}
		
		
		/*
		 * 
		 * EVENTS
		 * 
		 */
		override public function addMVCEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = true):void
		{
			this.addEventListener(type, listener, useCapture, priority, useWeakReference);
			
			if(_model)
			{
				_model.addEventListener(type, listener, useCapture, priority, useWeakReference);
			}
			
			if(_view)
			{
				_view.addEventListener(type, listener, useCapture, priority, useWeakReference);
			}
		}
		override public function dispatchMVCEvent(event:Event):Boolean
		{
			var bM:Boolean = _model ? _model.dispatchEvent(event) : true;
			var bV:Boolean = _view ? _view.dispatchEvent(event) : true;
			var bC:Boolean = this.dispatchEvent(event);
			
			return bM && bV && bC;
		}
		override public function hasMVCEventListener(type:String):Boolean
		{
			var bM:Boolean = _model ? _model.hasEventListener(type) : true;
			var bV:Boolean = _view ? _view.hasEventListener(type) : true;
			var bC:Boolean = this.hasEventListener(type);
			
			return bM && bV && bC;
		}
		override public function removeMVCEventListener(type:String, listener:Function, useCapture:Boolean = false):void
		{
			this.removeEventListener(type, listener, useCapture);
			
			if(_model)
			{
				_model.removeEventListener(type, listener, useCapture);
			}
			
			if(_view)
			{
				_view.removeEventListener(type, listener, useCapture);
			}
		}
	}
}